const nodeExcel = require('excel-export');
var fs = require('fs');


// 处理表头
function arrayAddattr(title) {
  const cos = []
  for (var i = 0; i < title.length; i++) {
    cos.push({ caption: title[i], width: 15 })
  }
  return cos
}

// 处理表row
function tabsRows(arr){
  var result = []
  arr.forEach((ele) => {
    Object.values(ele).forEach((value) => {
        result.push(value)
    })
    rowData.push(result)
  })
  return result;
}

let timefnc;
async function FsWrite(params, arr, title, reply ,special) {
  const conf = {};
  // 定义sheet名称
  conf.name = "JTSD";
  conf.cols = arrayAddattr(title)

  // console.log(conf)
  conf.rows = []
  var excelResult = nodeExcel.execute(conf);

  // 生成xlse
  fs.writeFile(`./${params.modelName}${params.createTime}.xlsx`, excelResult, 'binary', () => {
    console.log('文件已被保存')
    timefnc = setTimeout(() => {
      clearTimeout(timefnc)
      conf.rows = tabsRows(arr)
      excelResult = nodeExcel.execute(conf);
      fs.writeFile(`./${params.modelName}${params.createTime}.xlsx`, excelResult, 'binary', () => {
        console.log('文件已被保存222');
        // await ossPut(params, reply, 2)
      });
    })
    console.log('成功')
    return ossPut(params, reply, 1)
  })

}






// 本地文件上传oss
async function ossPut(params, reply, status) {
  params.createTime = new Date(params.createTime).getTime()
  let result = await client.put("数据导出/" + params.modelName + params.createTime + '.xlsx', './' + params.modelName + params.createTime + '.xlsx')
  if (result.res.status === 200) {
    fs.unlinkSync('./' + params.modelName + params.createTime + '.xlsx')
    let url = await client.signatureUrl("数据导出/" + params.modelName + params.createTime + '.xlsx'); //获取真实文件下载地址
    let insertStart = await insert(params, url, reply, status)
    return insertStart.data
  } else {
    return {
      "code": 0,
      "msg": "失败",
    }
  }
}

// 上传oss成功后上传深圳
async function insert(params, url, reply, status) {
  let source = 1; // 测试/生产为1, UAT为0
  let addressUrl;
  switch (process.env.NODE_ENV) {
    case 'dev':
      source = 1
      addressUrl = 'http://192.168.1.214:30525/download/report/file/insert'
      break;
    case 'test':
      source = 1
      addressUrl = 'http://test-jmsgw.jms.com/businessindicator/import/file/insert'
      break;
    case 'uat':
      source = 0
      addressUrl = 'https://uat-jmsgw.jtexpress.com.cn/businessindicator/import/file/insert'
      break;
    case 'prod':
      source = 1
      addressUrl = 'https://jmsgw.jtexpress.com.cn/businessindicator/import/file/insert'
      break;
    default:
      source = 1
      addressUrl = 'https://jmsgw.jtexpress.com.cn/businessindicator/import/file/insert'
      break;
  }
  const data = {
    "networkCode": params.networkCode,
    "networkName": params.networkName,
    "userId": params.userId,
    "userName": params.userName,
    "modelId": params.modelId,
    "status": status,
    "source": source,
    "downUrl": url,
    "version": params.version,
    "createTime": params.createTime,
    "updateTime": params.updateTime,
    "remark": params.remark,
    "modelName": params.modelName
  }
  console.log(addressUrl)
  return axios({
    method: 'POST',
    url: addressUrl,
    data: data,
    headers: { 'routeName': reply.request.headers.routename, 'authToken': reply.request.headers.authtoken }//设置header信息
  })
    .then((res) => {
      console.log(1111, process.env.NODE_ENV)
      if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') {
        res.data.url = url
      }
      console.log(res)
      return res
    }).catch((err) => {
      console.log(err)
      return err.response
    })
}

module.exports = {
  FsWrite,
  insert
}